package ch17;

import ch16.*;

import java.util.Spliterator;
import java.util.function.Consumer;

/**
 * Created by hasee on 2017/10/27.
 */
public class LinkedBinarySearchTree<T extends Comparable<T>>
        extends LinkedBinaryTree<T> implements BinarySearchTree<T>
{
    //-----------------------------------------------------------------
    //  Creates an empty binary search tree.
    //-----------------------------------------------------------------
    public LinkedBinarySearchTree()
    {
        super();
    }

    //-----------------------------------------------------------------
    //  Creates a binary search tree with the specified element at its
    //  root.
    //-----------------------------------------------------------------
    public LinkedBinarySearchTree (T element)
    {
        root = new BSTNode<T>(element);
    }

    //-----------------------------------------------------------------
    //  Adds the specified element to this binary search tree.
    //-----------------------------------------------------------------
    public void add (T item)
    {
        if (root == null)
            root = new BSTNode<T>(item);
        else
            ((BSTNode)root).add(item);
    }

    public T findMin() {
        ArrayIterator<T> i = new ArrayIterator<>();
        root.inorder(i);
        return i.get(0);
    }

    public T findMax() {
        ArrayIterator<T> i = new ArrayIterator<>();
        root.inorder(i);
        return i.get(size()-1);
    }

    //-----------------------------------------------------------------
    //  Removes and returns the element matching the specified target
    //  from this binary search tree. Throws an ElementNotFoundException
    //  if the target is not found.
    //-----------------------------------------------------------------
    public T remove (T target) throws ElementNotFoundException {
        BSTNode<T> node = null;

        if (root != null)
            node = ((BSTNode)root).find(target);

        if (node == null)
            throw new ElementNotFoundException ("Remove operation failed. "
                    + "No such element in tree.");

        root = ((BSTNode)root).remove(target);

        return node.getElement();
    }

    public void forEach(Consumer<? super T> action) {

    }
    public Spliterator<T> spliterator() {
        return null;
    }
}